<?php

namespace app\controller;

use app\model\XMLModel;
use app\service\ParsingXMLService;
use think\Collection;
use think\db\exception\DbException;
use think\facade\Queue;
use think\response\Json;

class ParsingXMLTaskPush extends BasicController
{

    protected XMLModel $XMLModel;

    public function initialize()
    {
        $this->XMLModel = new XMLModel();
    }

    public function pushParsingXMLTask(): Json
    {
        $ParsingXMLClassName = 'app\job\ParsingXML';
        $parsingXMLTask = "parsingXML";
        $successMessage = [];
        $errorMessage = [];
        $fileList = $this->loadFiles();
        foreach ($fileList as $value) {
            $isPushed = Queue::push( $ParsingXMLClassName , $value , $parsingXMLTask );
            if( $isPushed !== false ){
                $successMessage[] = "解析 {$value['file_name']} 任务发布成功 \n";
            }else{
                $errorMessage[] = "解析 {$value['file_name']} 任务发布出现错误 \n";
            }
        }
        return returnJson(200,"任务发布完成",[$successMessage,$errorMessage]);
    }

    /**
     * @return array[]
     * @throws \Exception
     */
    private function loadFiles(): array
    {
        $fileListArr = [];
        $fileList = $this->getUntreatedFile();
        foreach ($fileList as $key => $value) {
            $fileListArr[$key]["id"]       = $value["id"];
            $fileListArr[$key]["room_id"]   = $value["room_id"];
            $fileListArr[$key]["file_date"] = $value["file_date"];
            $fileListArr[$key]["file_path"] = $value["file_path"];
            $fileListArr[$key]["file_name"] = $value["file_name"];
        }
        return $fileListArr;
    }

    public function getUntreatedFile(): array|Collection
    {
        try {
            return $this->XMLModel->where("file_read", 0)->field("id,room_id,file_date,file_path,file_name")->select();
        } catch (DbException $e) {
            throw new \Exception("获取失败 ".$e->getMessage());
        }
    }
    /**
     * 验证文件是否合格
     * @param $fileListArr
     * @return array
     */
    public function validateXML(&$fileListArr): array
    {
        $errorXML = [];
        $parsingXMLService = new ParsingXMLService();
        foreach ($fileListArr as $key => $value) {
            if(true !== ($result = $parsingXMLService->validateXML($value))) {
                $errorXML[] = $result;
                unset($fileListArr[$key]);
            }
        }
        return $errorXML;
    }
}